package com.woniuxy.community_life.service.imp;

import com.woniuxy.community_life.dto.CommentDto;
import com.woniuxy.community_life.dto.DynamicDto;
import com.woniuxy.community_life.mapper.*;
import com.woniuxy.community_life.pojo.*;
import com.woniuxy.community_life.service.DynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DynamicServiceImp implements DynamicService {

    @Autowired
    private DynamicMapper dynamicMapper;
    @Autowired
    private DynamicImageMapper dynamicImageMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private RemitMapper remitMapper;
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addActiveDynamics(Dynamic dynamic, String filePath, MultipartFile[] imageFile) {
        DynamicImage dynamicImage = new DynamicImage();
        Date date = null;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(new Date());
            date = formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dynamic.setLastedTime(date);    //上传发布时间
        dynamic.setCreateTime(date);
        dynamicMapper.insertSelective(dynamic);
        Integer did = dynamic.getdId();
        dynamicImage.setdId(did);
        if (imageFile.length != 0) {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            //防止图片同名导致被覆盖
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  //创建时间戳区分
            for (int i = 0; i < imageFile.length; i++) {
                dynamicImage.setOrder(i + "");
                String filename = imageFile[i].getOriginalFilename();
                System.out.println(filename);
                String substring = filename.substring(filename.lastIndexOf("."));
                String newFileName = sdf.format(new Date()) + substring;    //得到新名字
                //服务器文件上传目录 F:\\CodeTestSaveLocation\hello.jpg
                try {
                    imageFile[i].transferTo(new File(filePath + File.separator + newFileName));
                    String substring1 = filePath.substring(filePath.lastIndexOf("CodeTestSaveLocation"));
                    String newFilePath="http://2480s85j10.wicp.vip:48906/";
                    dynamicImage.setUrl(newFilePath+substring1 + File.separator + newFileName);
                    dynamicImageMapper.insertSelective(dynamicImage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //展示广场
    @Override
    //@Cacheable(value = "tRemitid",key = "#tRemitid")
    public DynamicDto selectDynamic(Integer tRemitid) {
        List listAccout = new ArrayList();
        List listDynamicImages = new ArrayList();
        DynamicDto dynamicDto = new DynamicDto();
        Remit remit = remitMapper.selectByPrimaryKey(tRemitid);
        dynamicDto.setRemit(remit);
        List<Dynamic> message = dynamicMapper.getMessage(tRemitid);
        //dynamicDto.setMessage(message);
        for (Dynamic dynamic : message) {
            Integer getaId = dynamic.getaId();
            Integer getdId = dynamic.getdId();
            Account account = accountMapper.selectByPrimaryKey(getaId);
            List<DynamicImage> dynamicImages=dynamicImageMapper.selectImage(getdId);
            Integer clickCount = (Integer) redisTemplate.opsForValue().get("clickCount:dId" + getdId);
            if (clickCount==null||clickCount==0){
                clickCount=0;
            }
            dynamic.setClickCount(clickCount);
            listAccout.add(account);
            listDynamicImages.add(dynamicImages);
        }
        dynamicDto.setMessage(message);
        dynamicDto.setDynamicImages(listDynamicImages);
        dynamicDto.setAccount(listAccout);
        return dynamicDto;
    }

    //发布图片
    @Override
    public List<DynamicImage> selectImages(Integer dId) {
        return dynamicImageMapper.selectImage(dId);
    }

    //发布人昵称
    @Override
    public Account selectAccountNickName(Integer aId) {
        Account account = accountMapper.selectByPrimaryKey(aId);
        return account;
    }

    //展示发布评论 回复 回复数量 点赞人 点赞数量 发布消息信息
    @Override
    public CommentDto selectAllMessage(Integer dId) {
        CommentDto commentDto = new CommentDto();
        List<Account> accountLike = new ArrayList<>();
        List<Account> accountReply = new ArrayList<>();
        List<Account> accountFatherReply = new ArrayList<>();
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dId);
        Integer clickCount = (Integer) redisTemplate.opsForValue().get("clickCount:dId" + dId);
        if (clickCount==null||clickCount==0){
            clickCount=0;
        }
        dynamic.setClickCount(clickCount);
        commentDto.setMessage(dynamic);
        Set keys = redisTemplate.opsForHash().keys("dId:" + dId);
        for (Object getaId : keys) {
            System.out.println(getaId);
            //点赞人
            Integer aId =Integer.parseInt((String) getaId);
            Account account =accountMapper.selectByPrimaryKey(aId);
            accountLike.add(account);
        }
        commentDto.setAccountLike(accountLike);
        List<Comment> commentList=commentMapper.selectAllMessageBydId(dId);
        commentDto.setComments(commentList);
        if (commentList == null) {
            return null;
        }
        for (Comment comment : commentList) {
            Integer replyCId = comment.getReplyCId();   //回复（评论）种类id
            Integer replyAId = comment.getReplyAId(); //当前回复人id
            Account reply = accountMapper.selectByPrimaryKey(replyAId);  //回复（评论）人姓名
            accountReply.add(reply);
            Integer fatherReplyAId = comment.getFatherReplyAId();//被回复的那个人
            Account fatherReply = accountMapper.selectByPrimaryKey(fatherReplyAId);
            accountFatherReply.add(fatherReply);
        }
        commentDto.setAccountReply(accountReply);
        commentDto.setAccountFatherReply(accountFatherReply);

        return commentDto;
    }

    //添加评论回复
    @Override
    public void addReplyComment(Comment comment) {
        try {
            commentMapper.insertSelective(comment);
            Integer getdId = comment.getdId();
            Dynamic dynamic = dynamicMapper.selectByPrimaryKey(getdId);
            Integer commentCount = dynamic.getCommentCount();
            Integer  countComment = commentCount++;
            dynamic.setCommentCount(commentCount);
            dynamicMapper.updateByPrimaryKeySelective(dynamic);
        } catch (Exception e) {
            throw e;
        }
    }
//删除评论
    @Override
    public void removeComment(Integer comId,Integer aId) {
        try {
            Comment comment = commentMapper.selectByPrimaryKey(comId);//定位具体哪条评论
            Integer getdId = comment.getdId();
            Dynamic dynamic = dynamicMapper.selectByPrimaryKey(getdId);//定位具体哪条动态
            Integer commentCount = dynamic.getCommentCount();
            Integer  countComment = commentCount--;
            dynamic.setCommentCount(commentCount);
            dynamicMapper.updateByPrimaryKeySelective(dynamic);
            commentMapper.deleteComment(comId,aId);
        } catch (Exception e) {
            throw e;
        }
    }

    //添加点赞
    @Override
    public void addClickCount(Integer dId,Integer aId) {
        //取出用户id
        Integer clickCount=0;
        Map map = new HashMap();
        Like like = new Like();
        Date date = null;
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(new Date());
            date = formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        like.setLikeTime(date);
        like.setdId(dId);
        like.setaId(aId);
        map.put(aId+"", like);
        boolean isUser=redisTemplate.opsForSet().isMember("clickCount:user"+aId,dId);
        if (isUser){
            //redisTemplate.opsForValue().decrement("clickCount:dId" + dId);
            redisTemplate.delete("clickCount:user" + aId);
            redisTemplate.opsForValue().decrement("clickCount:dId" + dId);
            redisTemplate.opsForHash().delete("dId:"+dId, ""+aId);
        }else {
            redisTemplate.opsForSet().add("clickCount:user" + aId, dId);
            redisTemplate.opsForValue().increment("clickCount:dId" + dId);
            redisTemplate.opsForHash().putAll("dId:"+dId,map);
        }
    }
}
